#include <stdio.h>
#include <sys/stat.h>
#include <string.h>

#define FNAME_SIZE 30

void errorMsg(char msg[]) {
	printf("There was an error:\n%s\nThe program was terminated.\n",msg);
	return;
}

void main(int argc, char **argv) {
	long int cur, last, i;
	int c1, c2;
	char fName1[FNAME_SIZE], fName2[FNAME_SIZE], fNameOut[FNAME_SIZE];
	struct stat fStat1, fStat2;
	fpos_t fSize1, fSize2;
	FILE *fp1, *fp2, *fpOut;

	if (argc < 3) {
		errorMsg("You must supply all arguments.");
		return;
	}

	sprintf(fName1,"%s",argv[1]);
	sprintf(fName2,"%s",argv[2]);
	if (stat(fName1,&fStat1) != 0 || stat(fName1,&fStat2) != 0) {
		errorMsg("Please supply valid filenames.");
		return;
	}

	fSize1=fStat1.st_size;
	fSize2=fStat2.st_size;
	if (fSize1 != fSize2) {
		errorMsg("Files must be identical in size.");
		return;
	}

	fp1 = fopen(fName1,"rb");
	fp2 = fopen(fName2,"rb");
	strncpy(fNameOut,fName1,FNAME_SIZE);
	char *p = 0;
	p = strrchr(fNameOut,'.');
	if (p != 0) *p = '\0';
	strcat(fNameOut,".txt");
	fpOut = fopen(fNameOut,"w");

	fprintf(fpOut,"\tFile Differences\t\tSize\n");
	fprintf(fpOut,"New File:\t%-16s\t%d\n",fName1,fSize1);
	fprintf(fpOut,"Old File:\t%-16s\t%d\n",fName2,fSize2);
	fprintf(fpOut,"\nThe changes are:");

	cur=0;
	i=0;
	last = -1;
	c1 = getc(fp1);
	c2 = getc(fp2);

	while (c1 != EOF && c2 != EOF) {
		if (c1 != c2) {
			if (cur == last+1 && i!=0) {
				fprintf(fpOut," %0.2x", c1);
				i++;
				last=cur;
				if (i%0x10==0) i=0;
			} else {
				fprintf(fpOut,"\n0x%0.8x:\t%0.2x",ftell(fp1),c1);
				i=1;
				last=cur;
			}
		}
		c1 = getc(fp1);
		c2 = getc(fp2);
		cur++;
	}

	fprintf(fpOut,"\n\nGenerated by fcmp, by Eruanno");

	fclose(fp1);
	fclose(fp2);
	fclose(fpOut);
	return;
}